package com.library.controller;

import com.library.bean.User;
import com.library.service.UserService;
import com.library.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        UserService us = new UserServiceImpl();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map<String, Object> map = us.userLogin(username, password);
        System.out.println(username);
        if (map.get("success") != null) {
            User user = (User) map.get("success");
            System.out.println("User: " + user);
            request.getSession().setAttribute("LoginUser", user);
            request.getRequestDispatcher("/book").forward(request, response);
//            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else {
            String msg = (String) map.get("fail");
            request.setAttribute("msg", msg);
            // 改为 "login.jsp"
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 跳转到登录页面

    }
}
